#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flight策略演示模式
当网络连接不可用时，展示Flight策略的完整功能
"""

import os
import json
import time
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from dotenv import load_dotenv

load_dotenv()

def generate_mock_ohlcv_data(symbol: str, days: int = 7) -> pd.DataFrame:
    """生成模拟K线数据"""
    print(f"📊 生成 {symbol} 模拟数据...")
    
    # 基础价格
    base_prices = {
        'BTC/USDT:USDT': 96000,
        'ETH/USDT:USDT': 3600,
        'SOL/USDT:USDT': 210,
        'DOGE/USDT:USDT': 0.38
    }
    
    base_price = base_prices.get(symbol, 100)
    
    # 生成时间序列
    end_time = datetime.now()
    start_time = end_time - timedelta(days=days)
    
    timestamps = pd.date_range(start=start_time, end=end_time, freq='15T')
    
    # 生成价格数据
    np.random.seed(42)  # 固定种子以确保可重现性
    
    data = []
    current_price = base_price
    
    for i, timestamp in enumerate(timestamps):
        # 模拟价格波动
        price_change = np.random.normal(0, 0.002)  # 0.2%标准差
        trend = np.sin(i / 100) * 0.001  # 添加趋势
        
        current_price = current_price * (1 + price_change + trend)
        
        # 生成OHLC
        high = current_price * (1 + abs(np.random.normal(0, 0.001)))
        low = current_price * (1 - abs(np.random.normal(0, 0.001)))
        close = current_price
        open_price = data[-1]['close'] if data else close
        
        # 生成成交量（模拟天量事件）
        base_volume = np.random.normal(1000000, 200000)
        if i % 50 == 0:  # 每50根K线模拟一次天量
            base_volume *= np.random.uniform(3, 5)  # 3-5倍天量
        
        volume = max(base_volume, 100000)
        
        data.append({
            'timestamp': timestamp,
            'open': open_price,
            'high': high,
            'low': low,
            'close': close,
            'volume': volume
        })
    
    return pd.DataFrame(data)

def calculate_technical_indicators(df: pd.DataFrame) -> pd.DataFrame:
    """计算技术指标"""
    # SMA
    df['sma_7'] = df['close'].rolling(window=7).mean()
    df['sma_20'] = df['close'].rolling(window=20).mean()
    df['sma_50'] = df['close'].rolling(window=50).mean()
    df['sma_100'] = df['close'].rolling(window=100).mean()
    df['sma_200'] = df['close'].rolling(window=200).mean()
    
    # EMA和MACD
    df['ema_12'] = df['close'].ewm(span=12).mean()
    df['ema_26'] = df['close'].ewm(span=26).mean()
    df['macd'] = df['ema_12'] - df['ema_26']
    df['macd_signal'] = df['macd'].ewm(span=9).mean()
    df['macd_histogram'] = df['macd'] - df['macd_signal']
    
    # RSI
    delta = df['close'].diff()
    gain = (delta.where(delta > 0, 0)).rolling(14).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(14).mean()
    rs = gain / loss
    df['rsi'] = 100 - (100 / (1 + rs))
    
    # 布林带
    df['bb_middle'] = df['close'].rolling(20).mean()
    bb_std = df['close'].rolling(20).std()
    df['bb_upper'] = df['bb_middle'] + (bb_std * 2)
    df['bb_lower'] = df['bb_middle'] - (bb_std * 2)
    df['bb_position'] = (df['close'] - df['bb_lower']) / (df['bb_upper'] - df['bb_lower'])
    
    # 成交量指标
    df['volume_ma'] = df['volume'].rolling(20).mean()
    df['volume_ratio'] = df['volume'] / df['volume_ma']
    
    # 价格变化率
    df['price_change'] = df['close'].pct_change()
    df['price_change_5'] = df['close'].pct_change(5)
    
    return df.bfill().ffill()

def detect_volume_spike(df: pd.DataFrame, threshold: float = 3.0) -> dict:
    """检测天量成交量"""
    volume_ma = df['volume'].rolling(20).mean()
    spike_threshold = volume_ma.iloc[-1] * threshold
    
    recent_volume = df['volume'].tail(5)
    spike_candles = recent_volume[recent_volume > spike_threshold]
    
    consecutive_spikes = 0
    for vol in reversed(recent_volume.values):
        if vol > spike_threshold:
            consecutive_spikes += 1
        else:
            break
    
    return {
        'has_spike': len(spike_candles) > 0,
        'spike_count': len(spike_candles),
        'consecutive_spikes': consecutive_spikes,
        'latest_volume_ratio': recent_volume.iloc[-1] / volume_ma.iloc[-1],
        'spike_threshold': spike_threshold,
        'volume_ma': volume_ma.iloc[-1]
    }

def identify_key_levels(df: pd.DataFrame, lookback: int = 50) -> dict:
    """识别关键支撑阻力位"""
    current_price = df['close'].iloc[-1]
    
    recent_high = df['high'].tail(lookback).max()
    recent_low = df['low'].tail(lookback).min()
    
    # 斐波那契回撤位
    high_point = df['high'].tail(lookback).max()
    low_point = df['low'].tail(lookback).min()
    
    fib_diff = high_point - low_point
    fib_236 = high_point - fib_diff * 0.236
    fib_382 = high_point - fib_diff * 0.382
    fib_618 = high_point - fib_diff * 0.618
    fib_786 = high_point - fib_diff * 0.786
    
    tolerance = 0.02
    
    return {
        'resistance': recent_high,
        'support': recent_low,
        'fib_236': fib_236,
        'fib_382': fib_382,
        'fib_618': fib_618,
        'fib_786': fib_786,
        'near_resistance': abs(current_price - recent_high) / recent_high < tolerance,
        'near_support': abs(current_price - recent_low) / recent_low < tolerance,
        'near_fib_236': abs(current_price - fib_236) / fib_236 < tolerance,
        'near_fib_382': abs(current_price - fib_382) / fib_382 < tolerance,
        'near_fib_618': abs(current_price - fib_618) / fib_618 < tolerance,
        'near_fib_786': abs(current_price - fib_786) / fib_786 < tolerance,
    }

def detect_rsi_divergence(df: pd.DataFrame, periods: int = 14) -> dict:
    """检测RSI背离"""
    delta = df['close'].diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=periods).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=periods).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    
    # 简化的背离检测
    current_rsi = rsi.iloc[-1]
    current_price = df['close'].iloc[-1]
    
    # 模拟背离信号
    bearish_divergence = current_rsi > 70 and current_price > df['sma_20'].iloc[-1]
    bullish_divergence = current_rsi < 30 and current_price < df['sma_20'].iloc[-1]
    
    return {
        'rsi': current_rsi,
        'bearish_divergence': bearish_divergence,
        'bullish_divergence': bullish_divergence,
    }

def analyze_market_state(df: pd.DataFrame) -> dict:
    """分析市场状态"""
    current_price = df['close'].iloc[-1]
    
    sma_7 = df['sma_7'].iloc[-1]
    sma_20 = df['sma_20'].iloc[-1]
    sma_50 = df['sma_50'].iloc[-1]
    sma_200 = df['sma_200'].iloc[-1]
    
    # 趋势分析
    if current_price > sma_7 > sma_20:
        short_trend = "强势上涨"
    elif current_price > sma_7 and sma_7 < sma_20:
        short_trend = "震荡上涨"
    elif current_price < sma_7 < sma_20:
        short_trend = "强势下跌"
    else:
        short_trend = "震荡下跌"
    
    if current_price > sma_50 > sma_200:
        long_trend = "牛市"
    elif current_price < sma_50 < sma_200:
        long_trend = "熊市"
    else:
        long_trend = "震荡市"
    
    # 其他指标
    rsi = df['rsi'].iloc[-1]
    rsi_status = "超买" if rsi > 70 else "超卖" if rsi < 30 else "中性"
    
    macd = df['macd'].iloc[-1]
    macd_signal = df['macd_signal'].iloc[-1]
    macd_trend = "多头" if macd > macd_signal else "空头"
    
    bb_position = df['bb_position'].iloc[-1]
    bb_status = "上轨" if bb_position > 0.8 else "下轨" if bb_position < 0.2 else "中轨"
    
    return {
        'short_trend': short_trend,
        'long_trend': long_trend,
        'rsi': rsi,
        'rsi_status': rsi_status,
        'macd_trend': macd_trend,
        'bb_status': bb_status,
        'price_vs_sma7': ((current_price - sma_7) / sma_7) * 100,
        'price_vs_sma20': ((current_price - sma_20) / sma_20) * 100,
        'price_vs_sma50': ((current_price - sma_50) / sma_50) * 100,
    }

def generate_flight_signal(symbol: str, df: pd.DataFrame) -> dict:
    """生成Flight策略信号"""
    # 执行所有分析
    volume_analysis = detect_volume_spike(df)
    key_levels = identify_key_levels(df)
    rsi_divergence = detect_rsi_divergence(df)
    market_state = analyze_market_state(df)
    
    current_price = df['close'].iloc[-1]
    
    # Flight策略决策逻辑
    signal = "HOLD"
    strategy_used = "观望"
    confidence = "MEDIUM"
    reason = "市场状态不明，缺乏高质量交易机会"
    
    # 播种策略：趋势确认
    if (market_state['short_trend'] in ["强势上涨", "震荡上涨"] and 
        market_state['rsi_status'] in ["中性", "超卖"] and
        not rsi_divergence['bearish_divergence']):
        signal = "BUY"
        strategy_used = "播种"
        confidence = "HIGH"
        reason = "趋势向上，RSI未超买，符合播种策略入场条件"
    
    # 逆势刀锋策略：急跌后反弹
    elif (volume_analysis['has_spike'] and 
          key_levels.get('near_support', False) and
          market_state['short_trend'] in ["强势下跌", "震荡下跌"]):
        signal = "BUY"
        strategy_used = "逆势刀锋"
        confidence = "HIGH"
        reason = "天量+关键支撑+急跌，逆势刀锋策略捕捉反弹机会"
    
    # 背离策略
    elif rsi_divergence['bullish_divergence']:
        signal = "BUY"
        strategy_used = "背离"
        confidence = "HIGH"
        reason = "RSI看涨背离，价格新低但RSI不创新低，趋势反转信号"
    
    elif rsi_divergence['bearish_divergence']:
        signal = "SELL"
        strategy_used = "背离"
        confidence = "HIGH"
        reason = "RSI看跌背离，价格新高但RSI不创新高，趋势反转信号"
    
    # 计算止损止盈
    if signal == "BUY":
        stop_loss = current_price * 0.98  # 2%止损
        take_profit = current_price * 1.06  # 6%止盈
        risk_reward_ratio = 3.0
    elif signal == "SELL":
        stop_loss = current_price * 1.02  # 2%止损
        take_profit = current_price * 0.94  # 6%止盈
        risk_reward_ratio = 3.0
    else:
        stop_loss = current_price * 0.98
        take_profit = current_price * 1.06
        risk_reward_ratio = 1.5
    
    return {
        'signal': signal,
        'strategy_used': strategy_used,
        'confidence': confidence,
        'reason': reason,
        'stop_loss': stop_loss,
        'take_profit': take_profit,
        'risk_reward_ratio': risk_reward_ratio,
        'current_price': current_price,
        'volume_analysis': volume_analysis,
        'key_levels': key_levels,
        'rsi_divergence': rsi_divergence,
        'market_state': market_state
    }

def demo_flight_strategy():
    """Flight策略演示"""
    print("🎬 Flight策略演示模式")
    print("=" * 60)
    print("韩国顶级交易员Flight的小资金高倍率交易系统")
    print("三大策略：高倍率播种 + 逆势刀锋 + 量价背离")
    print()
    
    # Flight策略配置
    flight_config = {
        'leverage': 20,
        'position_size_ratio': 0.01,
        'daily_trade_limit': 10,
        'max_concurrent_positions': 3,
        'stop_loss_ratio': 0.02,
        'take_profit_ratio': 0.06,
        'symbols': [
            {'symbol': 'BTC/USDT:USDT', 'amount': 0.01},
            {'symbol': 'ETH/USDT:USDT', 'amount': 0.1},
            {'symbol': 'SOL/USDT:USDT', 'amount': 2},
            {'symbol': 'DOGE/USDT:USDT', 'amount': 1000}
        ]
    }
    
    print(f"⚙️ Flight策略配置:")
    print(f"   杠杆倍数: {flight_config['leverage']}x")
    print(f"   仓位比例: {flight_config['position_size_ratio']*100:.1f}%")
    print(f"   每日限额: {flight_config['daily_trade_limit']}次")
    print(f"   最大持仓: {flight_config['max_concurrent_positions']}个")
    print(f"   止损比例: {flight_config['stop_loss_ratio']*100:.1f}%")
    print(f"   止盈比例: {flight_config['take_profit_ratio']*100:.1f}%")
    print()
    
    # 分析每个交易对
    for symbol_config in flight_config['symbols']:
        symbol = symbol_config['symbol']
        print(f"📈 分析 {symbol}")
        print("-" * 40)
        
        # 生成模拟数据
        df = generate_mock_ohlcv_data(symbol)
        df = calculate_technical_indicators(df)
        
        # 生成Flight策略信号
        signal_data = generate_flight_signal(symbol, df)
        
        # 显示结果
        current_price = signal_data['current_price']
        print(f"💰 当前价格: ${current_price:,.2f}")
        print(f"📊 市场状态: {signal_data['market_state']['short_trend']} ({signal_data['market_state']['long_trend']})")
        print(f"📈 RSI状态: {signal_data['market_state']['rsi_status']} ({signal_data['rsi_divergence']['rsi']:.1f})")
        
        # 成交量分析
        vol_analysis = signal_data['volume_analysis']
        print(f"📊 成交量: {vol_analysis['latest_volume_ratio']:.2f}x {'🔥天量' if vol_analysis['has_spike'] else '📉正常'}")
        
        # 关键位分析
        key_levels = signal_data['key_levels']
        if key_levels.get('nearest_level'):
            nearest = key_levels['nearest_level']
            print(f"🎯 关键位: {nearest['name']} (${nearest['price']:.2f})")
        
        # 信号显示
        signal_emoji = {"BUY": "📈", "SELL": "📉", "HOLD": "⏸"}[signal_data['signal']]
        strategy_emoji = {"播种": "🌱", "逆势刀锋": "⚔️", "背离": "🔄", "观望": "⏸"}[signal_data['strategy_used']]
        confidence_emoji = {"HIGH": "🟢", "MEDIUM": "🟡", "LOW": "🔴"}[signal_data['confidence']]
        
        print(f"\n{signal_emoji} 信号: {signal_data['signal']}")
        print(f"{strategy_emoji} 策略: {signal_data['strategy_used']}")
        print(f"{confidence_emoji} 信心: {signal_data['confidence']}")
        
        if signal_data['signal'] != "HOLD":
            print(f"🛡️ 止损: ${signal_data['stop_loss']:,.2f}")
            print(f"🎯 止盈: ${signal_data['take_profit']:,.2f}")
            print(f"⚖️ 盈亏比: 1:{signal_data['risk_reward_ratio']:.1f}")
        
        print(f"📝 理由: {signal_data['reason']}")
        print()
    
    print("🎯 Flight策略演示完成")
    print("=" * 60)
    print("💡 注意：这是演示模式，使用模拟数据")
    print("🌐 实际交易需要网络连接到OKX API")
    print("📱 实盘运行请使用: python multi_account_manager.py")

if __name__ == "__main__":
    demo_flight_strategy()
